package com.fit.pages.user;

import org.apache.tapestry5.SelectModel;
import org.apache.tapestry5.annotations.Component;
import org.apache.tapestry5.annotations.InjectPage;
import org.apache.tapestry5.annotations.OnEvent;
import org.apache.tapestry5.annotations.Persist;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.corelib.components.Form;
import org.apache.tapestry5.ioc.Messages;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.ioc.services.PropertyAccess;
import org.apache.tapestry5.util.EnumSelectModel;

import com.fit.annotations.AdminAccess;
import com.fit.dao.employee.EmployeeDAO;
import com.fit.dao.user.UserDAO;
import com.fit.entities.Employee;
import com.fit.entities.User;
import com.fit.model.glov.GenericSelectModel;
import com.fit.model.user.MD5;
import com.fit.model.user.Type;
import com.fit.pages.ErrorPage;

@AdminAccess
public class EditUser {

	@Property
	@Persist
	private User user;

	@Inject
	private UserDAO userDAO;

	@Property
	private String newPassword;

	@Component
	private Form editForm;

	@InjectPage
	private ErrorPage errorPage;

	@Property
	@Persist
	private Type type;

	@Inject
	private EmployeeDAO employeeDAO;

	private GenericSelectModel<Employee> employees;

	@Property
	private Employee employee;

	@Inject
	private PropertyAccess access;

	@Inject
	private Messages messages;

	public GenericSelectModel<Employee> getEmployees() {
		employees = new GenericSelectModel<Employee>(employeeDAO.findAll(),
				Employee.class, "name", "jmbg", access);
		return employees;
	}

	public SelectModel getTypes() {
		return new EnumSelectModel(Type.class, messages);
	}

	Object onActivate(String username) {
		errorPage.setMessage("");
		User u = userDAO.findByUsername(username);
		if (u != null) {
			user = u;
		}
		if (user == null) {
			errorPage.setMessage("Error");
			return errorPage;
		}
		return null;
	}

	Object onSubmitFromEditForm() {
		try {
			if (newPassword != null) {
				user.setPassword(MD5.md5(newPassword));
			}
			if (type != null
					&& !user.getType().equalsIgnoreCase(type.toString())) {
				user.setType(type.toString());
			}
			if (employee != null && user.getEmployee() != employee) {
				user.setEmployee(employee);
			}
			userDAO.update(user);
			errorPage.setMessage("Successfully edited.");
			return errorPage;
		} catch (Exception e) {
			errorPage.setMessage("Error.");
			return errorPage;
		}
	}

	public boolean isEmployeeNotNull() {
		if (user.getEmployee() != null) {
			return true;
		}
		return false;
	}

	@OnEvent(component = "removeEmployeeLink")
	Object onRemoveCompanyLink() {
		user.setEmployee(null);
		return null;
	}

}
